﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using AutoMapper;
using Imladris.Entities;
using Imladris.BUS.DocumentRepoUOW;


namespace Imladris.Service.DocumentService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "DocService" in both code and config file together.
    public class DocService : IDocService
    {
        public List<DocumentDTO> GetAllDocuments()
        {
            using (var uow = new UnitOfWork())
            {
                using (var repo = new DocumentsRepo(uow))
                {
                    var result = repo.AllIncluding(c => c.DocumentRights,
                        d => d.DocumentChanges,
                        j => j.DocumentPersons);
                    result.ToList();
                    CreateDocumentToDocumentDTOMap();
                    List<DocumentDTO> documents = new List<DocumentDTO>();
                    
                    foreach (var document in result)
                    {
                        var doc = Mapper.Map<DocumentDTO>(document);
                        documents.Add(doc);
                    }
                    return documents;
                }
            }            
        }

        public void InsertOrUpdate(DocumentDTO document)
        {
            
            CreateDocumentDTOToDocumentMap();

            var doc = Mapper.Map<Document>(document);

            using (var uow = new UnitOfWork())
            {
                using (var documentsRepo = new DocumentsRepo(uow))
                {
                    documentsRepo.InsertOrUpdate(doc);
                    uow.Save();
                }
            }

            CreateDocumentToDocumentDTOMap();
            document = Mapper.Map<DocumentDTO>(doc);
        }

        #region Automapper

        private void CreateDocumentDTOToDocumentMap()
        {
            Mapper.CreateMap<DocumentDTO, Document>();
            Mapper.CreateMap<DocumentChangeDTO, DocumentChange>();
            Mapper.CreateMap<DocumentPersonDTO, DocumentPerson>();
            Mapper.CreateMap<DocumentRightDTO, DocumentRight>();
            Mapper.CreateMap<DocumentVersionDTO, DocumentVersion>();
        }

        private void CreateDocumentToDocumentDTOMap()
        {
            Mapper.CreateMap<Document, DocumentDTO>();
            Mapper.CreateMap<DocumentChange, DocumentChangeDTO>();
            Mapper.CreateMap<DocumentPerson, DocumentPersonDTO>();
            Mapper.CreateMap<DocumentRight, DocumentRightDTO>();
            Mapper.CreateMap<DocumentVersion, DocumentVersionDTO>();
        }

        #endregion
    }
}
